package controller.setting;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.trek2000.android.enterprise.Enterprise;
import com.trek2000.android.enterprise.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import adapter.company.AllCompanyFeedAdapter;
import controller.company.SelectCompanyAsync;
import define.API;
import define.Key;
import model.company.CompanyFeedItem;
import model.company.ShotOfCompanyFeedItem;
import model.settting.SettingItem;
import ui.fragment.company.AllCompanyFeedFragment;
import ui.fragment.setting.SettingFragment;
import utils.Utils;

/**
 * Created by trek2000 on 19/8/2014.
 */
public class SettingAsync extends AsyncTask<String, Void, Boolean> {

    /**
     * String section
     */
    private String ADDRESS = "";
    private String AFFLIATIONS = "";
    private double allocated_space = 0;
    private String CITY = "";
    private long company_id = 0;
    private String COMPANY_LOGO = "";
    private String COMPANY_NAME = "";
    private int company_id_group = 0;
    private String COUNTRY_ID = "" ;
    private String DESCRIPTION = "";
    private int employee_pass = 0;
    private String FORMAL_NAME = "";
    private int mobile_country_code = 0;
    private int number_of_users = 0;
    private int office_country_code = 0;
    private int office_number = 0;
    private long paypal_address = 0;
    private long phone_number = 0;
    private long postcode = 0;
    private String STATE = "";
    private double used_space = 0;

    private String ERROR = "";
    private String STATUS = "";

    /**
     * View section
     */

    /**
     * The others section
     */
    private Context mContext;
    public static ArrayList <CompanyFeedItem> mAlAllCompanyFeed = new ArrayList<>();
    public static ArrayList <Long> mAlGroupId = new ArrayList<>();
    public static ArrayList <Long> mAlShotId = new ArrayList<>();

    public SettingAsync(Context context) {
        this.mContext = context;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        return getData(params);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        // hide waiting dialog
        Utils.hideWaitingDialog();

        if (!result) {
            Toast.makeText(mContext, ERROR ,
                    Toast.LENGTH_SHORT).show();
        } else {
            SettingFragment.displayDataToViewSettingFragment(Enterprise.setting.getSettingItem());
        }
    }

    /**
     * Basic methods
     */

    private boolean getData(String[] params) {
        HttpPost mHttpPost = new HttpPost(API.GET_COMPANY_DETAILS);
        List<NameValuePair> mListValues = new ArrayList<NameValuePair>();
        /**
         * user_Name
         * password
         * device_token
         * device_OS
         */
        mListValues.add(new BasicNameValuePair(Key.USER_GLOBAL_ID, params[0]));
        mListValues.add(new BasicNameValuePair(Key.ACCESS_TOKEN, params[1]));
        mListValues.add(new BasicNameValuePair(Key.COMPANY_ID, params[2]));
        mListValues.add(new BasicNameValuePair(Key.COMPANY_ID_GROUP, params[3]));

        try {
            mHttpPost.setEntity(new UrlEncodedFormEntity(mListValues));
            HttpParams mHttpParams = new BasicHttpParams();

            int TIMEOUT_CONNECTION = 30000;
            int TIMEOUT_SOCKET = 30000;

            HttpConnectionParams.setConnectionTimeout(
                    mHttpParams, TIMEOUT_CONNECTION);
            HttpConnectionParams.setSoTimeout(mHttpParams, TIMEOUT_SOCKET);
            HttpClient mHttpclient = new DefaultHttpClient(mHttpParams);
            HttpResponse mHttpResponse;
            mHttpResponse = mHttpclient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            String XML = EntityUtils.toString(mHttpEntity);

            Log.i("", SettingAsync.class.getSimpleName() + " " + XML);

            JSONObject mJoXml = new JSONObject(XML);
            //get string in mJoXml
            STATUS = mJoXml.getString(Key.STATUS);
            if (STATUS.equals(mContext.getString(R.string.success_))) {
                //get mJoCompany in mJoXml
                JSONObject mJoCompany = mJoXml.getJSONObject(Key.COMPANY);
                //get string in mJoCompany
                ADDRESS =mJoCompany.getString(Key.ADDRESS);
                AFFLIATIONS = mJoCompany.getString(Key.AFFLIATIONS);
                allocated_space = mJoCompany.getDouble(Key.ALLOCATED_SPACE);
                CITY = mJoCompany.getString(Key.CITY);
                company_id = mJoCompany.getLong(Key.COMPANY_ID);
                COMPANY_LOGO = mJoCompany.getString(Key.COMPANY_LOGO);
                COMPANY_NAME = mJoCompany.getString(Key.COMPANY_NAME);
                company_id_group = mJoCompany.getInt(Key.COMPANY_ID_GROUP);
                COUNTRY_ID = mJoCompany.getString(Key.COUNTRY_ID) ;
                DESCRIPTION = mJoCompany.getString(Key.DESCRIPTION);
                employee_pass = mJoCompany.getInt(Key.EMPLOYEE_PASS);
                FORMAL_NAME = mJoCompany.getString(Key.FORMAL_NAME);
                mobile_country_code = mJoCompany.getInt(Key.MOBILE_COUNTRY_CODE);
                number_of_users = mJoCompany.getInt(Key.NUMBER_OF_USERS);
                office_country_code = mJoCompany.getInt(Key.OFFICE_COUNTRY_CODE);
                office_number = mJoCompany.getInt(Key.OFFICE_NUMBER);
                paypal_address = mJoCompany.getLong(Key.PAYPAL_ADDRESS);
                phone_number = mJoCompany.getLong(Key.PHONE_NUMBER);
                postcode = mJoCompany.getLong(Key.POSTCODE);
                STATE = mJoCompany.getString(Key.STATE);
                used_space = mJoCompany.getDouble(Key.USED_SPACE);

                SettingItem settingItem = new SettingItem(
                        ADDRESS, AFFLIATIONS, allocated_space,
                        CITY, company_id, COMPANY_LOGO,
                        COMPANY_NAME, company_id_group, COUNTRY_ID,
                        DESCRIPTION, employee_pass, FORMAL_NAME,
                        mobile_country_code, number_of_users, office_country_code,
                        office_number, paypal_address, phone_number,
                        postcode, STATE, used_space
                );

                //save setting item to single ton
                Enterprise.setting.setSettingItem(settingItem);

                return  true;
            } else if (STATUS.equals(mContext.getString(R.string.error))) {
                ERROR = mJoXml.getString(Key.ERROR);
                return false;
            }
        } catch (ClassCastException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}